<template>
    <div class="b-skeleton" :class="{ 'b-skeleton-animated': animated }">
        <template v-if="loading">
            <slot name="skeleton">
                <div class="skeleton-img" v-if="type === 'image'"></div>
            </slot>
            <div v-for="(item, index) in rows" :key="item" class="skeleton-item" :style="itemStyle(index)"></div>
        </template>
        <slot v-else></slot>
    </div>
</template>
<script setup lang="ts">
import { ref, computed, Ref } from 'vue'

interface Config {
    index: number;
    style: object;
}
interface IProps {
    loading: boolean;
    type: string;
    animated?: boolean;
    rows?: number;
    itemHeight?: number | null;
    configList?: Config[];
    background?: string | null
}
const props = withDefaults(defineProps<IProps>(), {
    loading: true,
    type: 'div',
    animated: false,
    rows: 3,
    itemHeight: null,
    configList: [],
    background: null
})
const itemStyle = (index) => {
    let style = {}
    if (props.background) style.background = props.background
    if (props.itemHeight) style.height = `${props.itemHeight}px`
    if (props.configList?.length) {
        const target = props.configList.find(item => item.index === index)
        if (target) {
            style = {
                ...style,
                ...target.style
            }
        }
    }
    return style;
}
</script>

<style lang='less' scoped>
@keyframes skeleton-loading {
    0% {
        background-position: 100% 50%;
    }

    100% {
        background-position: 0 50%;
    }
}

.b-skeleton {
    width: 100%;
    .skeleton-img{
        width: 100px;
        height: 100px;
        border-radius: 5px;
        margin-bottom: 16px;
        background: #eeeeee;
    }

    .skeleton-item {
        height: 16px;
        border-radius: 5px;
        margin-bottom: 16px;
        background: #eeeeee;
    }

    &-animated {
        .skeleton-item,
        .skeleton-img {
            background: linear-gradient(90deg, #f2f2f2 25%, #ececec 37%, #f2f2f2 63%);
            background-size: 400% 100%;
            animation: skeleton-loading 1.2s ease infinite;
        }
    }
}
</style>